import {defineStore} from 'pinia'
import type {FrontUserLoginDTO} from '@/api/front/user/type'
import {reqLogin, reqGetLoginUser, reqLogout} from "@/api/front/user";
import {setToken, removeToken} from '@/utils/token';
import {ElMessage} from "element-plus";
import router from "@/router";

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            isLogin: false,
            userName: '',
            avatar: '',
            nickname: '',
            userId: '',
            loginDialogVisible:false
        }
    },
    getters: {},
    actions: {
        async userLogin(loginForm: FrontUserLoginDTO) {
            return new Promise(async resolve => {
                const loginRes = await reqLogin(loginForm)
                console.log("返回",loginRes)
                if (loginRes.code == 200) {
                    setToken(loginRes.data)
                    await this.modifyUserInfo()
                    resolve(true)
                }
                else {
                    ElMessage.error("登录失败！")
                    resolve(false)
                }
            })

        },
        async modifyUserInfo() {
            const loginUserRes = await reqGetLoginUser()
            this.userName = loginUserRes.data.userName
            this.avatar = loginUserRes.data.avatar
            this.userId = loginUserRes.data.userId
            this.nickname = loginUserRes.data.nickname
            this.isLogin = true
        },
        showLoginDialog(){
            this.loginDialogVisible=true
        },
        hideLoginDialog(){
            this.loginDialogVisible=false
        },
        userLogout() {
            this.$reset()
            removeToken()
            reqLogout()
            router.push('/login')
        }
    },
    persist: {
        storage: sessionStorage,
    }
})
